package com.tinyideatech.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tinyideatech.common.utils.StringUtils;
import com.tinyideatech.common.utils.http.HttpClientUtil;
import com.tinyideatech.system.entity.CarCode;
import com.tinyideatech.system.entity.CarDevice;
import com.tinyideatech.system.mapper.CarCodeMapper;
import com.tinyideatech.system.mapper.CarDeviceMapper;
import com.tinyideatech.system.service.ICarDeviceService;
import mypackage.DevelopmentServiceDelegate;
import mypackage.DevelopmentServiceServiceLocator;
import mypackage.Feature;
import mypackage.SerialNumber;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhangy-5
 * @date 2019-09-09
 */
@Service
public class CarDeviceServiceImpl extends ServiceImpl<CarDeviceMapper, CarDevice> implements ICarDeviceService {

    private static final Logger logger = LoggerFactory.getLogger(CarDeviceServiceImpl.class);

    @Autowired
    private CarCodeMapper carCodeMapper;

    @Autowired
    private CarDeviceMapper carDeviceMapper;


    @Value("${url.security}")
    private String URL;

    @Value("${url.bind}")
    private String BIND_URL;

    @Override
    public void changeStatus(CarDevice carDevice) {

    }

    @Override
    public boolean bindCode2Device(String deviceId, String code) {
        try {
            CarCode query = carCodeMapper.selectById(
                    new QueryWrapper<>().eq("device_id", deviceId));
            if (StringUtils.isNotNull(query.getCode())) {
                logger.info("设备和激活码已绑定");
                return false;
            } else {
                query.setCode(code);
                query.setCreateBy("admin");
                query.setCreateTime(new Date());
                query.setProducts("Androi AHD 3D RoundView");
                query.setTemplates(null);
                query.setFeatures(0);
                int result = carCodeMapper.updateById(query);
                if (result == 1) {
                    logger.info("设备和激活码成功");
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设备和激活码绑定失败");
        }
        return false;
    }

    @Override
    public int bindCode2Mobile(String deviceId, String mobile, String code, String pwd) throws Exception {
        // 调用注册，注册：成功；不成功
        Map<String, String> params = new HashMap<>();
        params.put("mobile", mobile);
        params.put("password", pwd);
        params.put("code", code);
        List<NameValuePair> paramsList = HttpClientUtil.getParams(params);
        JSONObject http = HttpClientUtil.sendPost(URL, paramsList, null);
        // 注册成功
        if (http.getInteger("status") == 200) {
            return bindRequest(deviceId, mobile);
        } else if (http.getInteger("status") == 400) {
            String entity = http.getString("entity");
            logger.info(String.format("[%s]", entity));
            if (entity.contains("用户名已存在")) {
                return bindRequest(deviceId, mobile);
            }
            // 注册验证码失败
            return 302;
        } else {
            // 内部错误
            return 500;
        }
    }

    @Override
    public Integer verifyCode(String code) {
        DevelopmentServiceServiceLocator locator =
                new DevelopmentServiceServiceLocator();
        DevelopmentServiceDelegate service;
        try {
            service = locator.getDevelopmentServicePort();
            SerialNumber serialNumber = service.getSnDetail(code);
            Feature[] features = serialNumber.getFeature();
            for (Feature feature : features) {
                if (feature.getName().equals("ADAS")) {
                    int value = feature.getValue();
                    if (value == 1 || value == 12 || value == 123) {
                        return value;
                    }
                }
            }
        } catch (ServiceException | RemoteException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Integer verifyRmon(String deviceId) {
        return carDeviceMapper.selectOne(new QueryWrapper<CarDevice>().eq("device_id", deviceId)).getDeviceRmon();
    }

    private int bindRequest(String deviceId, String mobile) throws Exception {
        // 调用绑定
        Map<String, String> bind_params = new HashMap<>();
        bind_params.put("clientId", deviceId);
        bind_params.put("mobile", mobile);
        bind_params.put("code", "999999");
        List<NameValuePair> bind_paramsList = HttpClientUtil.getParams(bind_params);
        JSONObject bind_http = HttpClientUtil.sendPost(BIND_URL, bind_paramsList, null);
        String entity = bind_http.getString("entity");
        logger.info(String.format("[%s]", entity));
        // 绑定调用成功
        if (bind_http.getInteger("status") == 200) {
            CarDevice carDevice = carDeviceMapper.selectOne(new QueryWrapper<CarDevice>()
                    .eq("device_id", deviceId));
            if (carDevice != null) {
                carDevice.setMobile(mobile);
                carDevice.setUpdateTime(new Date());
                carDeviceMapper.updateById(carDevice);
                return 0;
            } else {
                CarDevice registry = new CarDevice();
                registry.setDeviceId(deviceId);
                registry.setMobile(mobile);
                registry.setCreateTime(new Date());
                registry.setCreateBy("admin");
                carDeviceMapper.insert(registry);
                return 0;
            }
        }
        // 绑定失败
        return 301;
    }
}
